package com.yhm.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Component;

import com.yhm.dao.AllDAO;
import com.yhm.model.OrderFrom;
import com.yhm.model.Redo;
import com.yhm.model.Trace;
import com.yhm.service.XlsManager;
import com.yhm.util.page.OrderPage;
import com.yhm.vo.OrderFromBean;

@Component("xlsManager")
public class XlsManagerImpl implements XlsManager{
	
	private AllDAO allDAO = new AllDAO();
	
	private SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

	@SuppressWarnings("unchecked")
	public InputStream get_order_list_xml(OrderPage page,String env) throws ParseException{
		String string_order = "";
		List<OrderFromBean> order_bean_list = new ArrayList<OrderFromBean>();
		if (page.getCompanyNum().length() != 3) {
			page.setCompanyNum("");
		}
		if (page.getSerial_number().length() != 4) {
			page.setSerial_number("");
		}
		if (page.getSelImportant().length() != 4) {
			page.setSelImportant("");
		}
		if (page.getCompanyNum().length()!=0&&page.getSerial_number().length()!=0&&page.getSelImportant().length()!=0) {
			string_order = "o.companyNum like '"+page.getCompanyNum()+"_____"+page.getSerial_number()+""+page.getSelImportant()+"'";
		}
		if (page.getCompanyNum().length()!=0&&page.getSerial_number().length()!=0&&page.getSelImportant().length()==0) {
			string_order = "o.companyNum like '"+page.getCompanyNum()+"_____"+page.getSerial_number()+"____'";
		}
		if (page.getCompanyNum().length()!=0&&page.getSerial_number().length()==0&&page.getSelImportant().length()!=0) {
			string_order = "o.companyNum like '"+page.getCompanyNum()+"_________"+page.getSelImportant()+"'";
		}
		if (page.getCompanyNum().length()==0&&page.getSerial_number().length()!=0&&page.getSelImportant().length()!=0) {
			string_order = "o.companyNum like '________"+page.getSerial_number()+""+page.getSelImportant()+"'";
		}
		if (page.getCompanyNum().length()!=0&&page.getSerial_number().length()==0&&page.getSelImportant().length()==0) {
			string_order = "o.companyNum like '"+page.getCompanyNum()+"_____________'";
		}
		if (page.getCompanyNum().length()==0&&page.getSerial_number().length()!=0&&page.getSelImportant().length()==0) {
			string_order = "o.companyNum like '________"+page.getSerial_number()+"____'";
		}
		if (page.getCompanyNum().length()==0&&page.getSerial_number().length()==0&&page.getSelImportant().length()!=0) {
			string_order = "o.companyNum like '____________"+page.getSelImportant()+"'";
		}
		
		if (page.getCustomNum().length() != 0) {
			if (string_order.length() == 0)
				string_order = string_order + " " + "o.customNum like" + " " + "'%"
						+ page.getCustomNum() + "%'";
			else {
				string_order = string_order + " " + "and" + " " + "o.customNum like" + " " + "'%"
						+ page.getCustomNum() + "%'";
			}
		}
		
		if (page.getCustomType().length() != 0) {
			if (string_order.length() == 0)
				string_order = string_order + " " + "o.customType like" + " " + "'%"
						+ page.getCustomType() + "%'";
			else {
				string_order = string_order + " " + "and" + " " + "o.customType like" + " " + "'%"
						+ page.getCustomType() + "%'";
			}
		}
		if (page.getMarks().length() != 0) {
			if (string_order.length() == 0)
				string_order = string_order + " " + "o.marks like" + " " + "'%" + page.getMarks() + "%'";
			else {
				string_order = string_order + " " + "and" + " " + "o.marks like" + " " + "'%"
						+ page.getMarks() + "%'";
			}
		}
		if (page.getMovement().length() != 0) {
			if (string_order.length() == 0)
				string_order = string_order + " " + "o.movement like" + " " + "'%" + page.getMovement()
						+ "%'";
			else {
				string_order = string_order + " " + "and" + " " + "o.movement like" + " " + "'%"
						+ page.getMovement() + "%'";
			}
		}
		if(page.getBegin_time().length()!=0&&page.getEnd_time().length()!=0){
			if (string_order.length() == 0)
				string_order = string_order + " " + "(o.makeTime between '"+page.getBegin_time()+"' and '"+page.getEnd_time()+"')";
			else {
				string_order = string_order + " " + "and" + "(o.makeTime " + "between '"+page.getBegin_time()+"' and '"+page.getEnd_time()+"')";
			}
		}
		if(page.getBegin_time().length()==0&&page.getEnd_time().length()!=0){
			if (string_order.length() == 0)
				string_order = string_order + " " + "(o.makeTime between '2012-10-10' and '"+page.getEnd_time()+"')";
			else {
				string_order = string_order + " " + "and" + "(o.makeTime " + "between '2012-10-10' and '"+page.getEnd_time()+"')";
			}
		}
		if(page.getBegin_time().length()!=0&&page.getEnd_time().length()==0){
			Date date = new Date();
			String now = df.format(date);
			if (string_order.length() == 0)
				string_order = string_order + " " + "(o.makeTime between '"+page.getBegin_time()+"' and '"+now+"')";
			else {
				string_order = string_order + " " + "and" + "(o.makeTime " + "between '"+page.getBegin_time()+"' and '"+now+"')";
			}
		}
		if(!page.getDep().equals("0")){
			if (string_order.length() == 0)
				string_order = string_order + " " + "o.department like" + " " + "'%" + page.getDep()
						+ "%'";
			else {
				string_order = string_order + " " + "and" + " " + "o.department like" + " " + "'%"
						+ page.getDep() + "%'";
			}
		}
		String hql = "";
		if(string_order.length()==0){
			if(page.getStatus().equals("0")){
				hql = "from OrderFrom o where o.qc2 = '"+page.getStatus()+"'";
			}else{
				hql = "from OrderFrom o where o.qc2 != '0'";
			}
		}else{
			if(page.getStatus().equals("0")){
				hql = "from OrderFrom o where o.qc2 = '"+page.getStatus()+"' and " + string_order +"";
			}else{
				hql = "from OrderFrom o where o.qc2 != '0' and " + string_order +"";
			}
		}
		
		List<OrderFrom> order_list = (List<OrderFrom>) allDAO.getOrderFromDAO().findhql(hql);
		
		String trace_hql = "";
		if(page.getStatus().equals("0")){
			trace_hql = "from Trace t where t.companyNum in(select o.companyNum from OrderFrom o where o.qc2 = '"+page.getStatus()+"')";
		}else{
			trace_hql = "from Trace t where t.companyNum in(select o.companyNum from OrderFrom o where o.qc2 != '0')";
		}
		List<Trace> trace_list = (List<Trace>) allDAO.getTraceDAO().findhql(trace_hql);
		
		String redo_hql = "";
		if(page.getStatus().equals("0")){
			redo_hql = "from Redo r where r.companyNum in(select o.companyNum from OrderFrom o where o.qc2 = '"+page.getStatus()+"')";
		}else{
			redo_hql = "from Redo r where r.companyNum in(select o.companyNum from OrderFrom o where o.qc2 != '0')";
		}
		List<Redo> redo_list = (List<Redo>) allDAO.getRedoDAO().findhql(redo_hql);
		
		Iterator<OrderFrom> order_iterator=order_list.iterator();
		OrderFrom of = null;
		while(order_iterator.hasNext()){
			of = order_iterator.next();
			
			List<Trace> ltrace = new ArrayList<Trace>();
			Iterator<Trace> trace_iterator=trace_list.iterator();
			while(trace_iterator.hasNext()){
				Trace tr = trace_iterator.next();
				if(tr.getCompanyNum().equals(of.getCompanyNum())){
					ltrace.add(tr);
				}
			}
			Collections.sort(ltrace,new Comparator<Trace>(){
		        public int compare(Trace arg0, Trace arg1) {
		            return arg1.getRegtime().compareTo(arg0.getRegtime());
		        }
		    });
			
			String dep = "";
			String time = "";
			String qc1 = "";
			String qc2 = "";
			String process = "";
			String regtime = "";
			if(ltrace==null||ltrace.size()==0){
				dep = "写字楼";
				Date begin = df.parse(of.getMakeTime());
				Date end = df.parse(df.format(new Date()));
				long between = (end.getTime() - begin.getTime()) / 1000;// 除以1000是为了转换成秒
				long day1 = between / (24 * 3600);
				time = "停留" + day1 + "天";
				regtime = of.getMakeTime();
			}else{
				dep = ltrace.get(0).getDepartment();
				if (ltrace.get(0).getOuttime() == null){
					Date begin = dfs.parse(ltrace.get(0).getRegtime());
					Date end = dfs.parse(dfs.format(new Date()));
					time = "停留"+OrderManagerImpl.time_difference(begin,end);
				}else if(ltrace.get(0).getOuttime()!=null){
					time = "已离开";
				}
				regtime = ltrace.get(0).getRegtime();
			}
			if(of.getQc1().equals("0")){
				qc1 = "未检查";
			}else{
				qc1 = of.getQc1()+"号检查";
			}
			if(of.getQc2().equals("0")){
				qc2 = "未出货";
			}else{
				qc2 = of.getQc2()+"号检查";
			}
			for(Trace t : ltrace){
				process = t.getDepartment() +"=>"+ process;
			}
			process = "写字楼=>" + process;
			process = process.substring(0, process.length()-2);
			
			List<Redo> lredo = new ArrayList<Redo>();
			Iterator<Redo> redo_iterator=redo_list.iterator();
			while(redo_iterator.hasNext()){
				Redo re = redo_iterator.next();
				if(re.getCompanyNum().equals(of.getCompanyNum())){
					lredo.add(re);
				}
			}
			
			String redoInfo = "";
			for(Redo re : lredo){
				redoInfo = redoInfo + re.getDepartment() +"重做"+ re.getRedoNum() + "次；";
			}
			
			OrderFromBean ob = new OrderFromBean();
			ob.setCompanyNum(of.getCompanyNum());
			ob.setCustomNum(of.getCustomNum());
			ob.setCustomType(of.getCustomType());
			ob.setMakeTime(of.getMakeTime());
			ob.setMovement(of.getMovement());
			ob.setNum(of.getNum());
			ob.setRegtime(regtime);
			ob.setMarks(of.getMarks());
			ob.setDepartment(dep);
			ob.setQc1(qc1);
			ob.setQc2(qc2);
			ob.setStatus(time);
			ob.setProcess(process);
			ob.setRedoInfo(redoInfo);
			order_bean_list.add(ob);
		}
		InputStream is = create_order_list_xml(order_bean_list,env);
		return is;
	}
	
	
	
	
	public static InputStream create_order_list_xml(List<OrderFromBean> orderBean_list,String env) {
		String[] order = {  "编号", "下单时间","当前部门","到达时间","状态","流程","QC1检查员","QC2检查员","重做信息","客户编号", "客户型号", "唛头", "机芯", "数量"};
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet(env);
		HSSFRow row = sheet.createRow(0);
		for (int i = 0; i < 14; i++) {
			HSSFCell cell = row.createCell(i);
			cell.setCellType(1);
			cell.setCellValue(order[i]);
		}
		int x = 1;
		for (OrderFromBean ob : orderBean_list) {
			HSSFRow row2 = sheet.createRow((short) x);
			String[] com = new String[16];
			if (ob.getCompanyNum() != null) com[0] = ob.getCompanyNum();
			else com[0] = null;
			
			if (ob.getMakeTime() != null) com[1] = ob.getMakeTime();
			else com[1] = null;
			
			if (ob.getDepartment() != null) com[2] = ob.getDepartment();
			else com[2] = null;
			
			if (ob.getRegtime() != null) com[3] = ob.getRegtime();
			else com[3] = null;
			
			if (ob.getStatus() != null) com[4] = ob.getStatus();
			else com[4] = null;
			
			if (ob.getProcess() != null) com[5] = ob.getProcess();
			else com[5] = null;
			
			if (ob.getQc1() != null) com[6] = ob.getQc1();
			else com[6] = null;

			if (ob.getQc2() != null) com[7] = ob.getQc2();
			else com[7] = null;

			if (ob.getRedoInfo() != null) com[8] = ob.getRedoInfo();
			else com[8] = null;
			
			if (ob.getCustomNum() != null) com[9] = ob.getCustomNum();
			else com[9] = null;
			
			if (ob.getCustomType() != null) com[10] = ob.getCustomType();
			else com[10] = null;
			
			if (ob.getMarks() != null) com[11] = ob.getMarks();
			else com[11] = null;
			
			if (ob.getMovement() != null) com[12] = ob.getMovement();
			else com[12] = null;
			
			if (ob.getNum() != null) com[13] = ob.getNum();
			else com[13] = null;
			
			for (int i = 0; i < 14; i++) {
				HSSFCell cell = row2.createCell(i);
				cell.setCellType(1);
				cell.setCellValue(com[i]);
			}
			x++;
		}
		String xml_path = XlsManagerImpl.class.getResource("/").getPath()
				.replaceAll("WEB-INF/classes/", "temp");
		try {
			if (!new File(xml_path).isDirectory())
				new File(xml_path).mkdir();
		} catch (SecurityException e) {
			System.out.println("can   not   make   directory ");
		}

		StringBuffer sb = new StringBuffer(env);
		File file = new File(xml_path + "/" + sb.append(".xls").toString());
		try {
			OutputStream os = new FileOutputStream(file);
			try {
				workbook.write(os);

				os.close();
			} catch (IOException localIOException) {
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

		InputStream xml_is = null;
		try {
			xml_is = new FileInputStream(file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return xml_is;
	}
	
	
	
	public AllDAO getAllDAO() {
		return allDAO;
	}
	
	@Resource(name = "allDAO")
	public void setAllDAO(AllDAO allDAO) {
		this.allDAO = allDAO;
	}
}
